package com.neuedu.android.helloworld;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {
    private Button btnLogin; //按钮
    TextView tvForgetPassword;
    TextView etUserName;
    TextView etPassword;
    CheckBox autoLogin;
    ProgressDialog dialog;

    //Activity  UI线程 用于更新界面
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //结束之后关闭 弹出层
            if (dialog != null) {
                dialog.dismiss();
            }

            int what = msg.what;
            if (what == 1) {//网络请求成功
                Map<String, Object> result = (Map) msg.obj;
                Double code = (double) result.get("code");
                String error = (String) result.get("message");
                if (code == 200) {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                    //saveAutoLogin
                    saveAutoLogin();

                    Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();

                } else {
                    Toast.makeText(LoginActivity.this, error, Toast.LENGTH_SHORT).show();
                }
            } else if (what == 2) {
                Toast.makeText(LoginActivity.this, "APP请求失败,请联系管理员", Toast.LENGTH_SHORT).show();
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        //设置完布局文件
        setContentView(R.layout.activity_login);
        //找到按钮
        btnLogin = findViewById(R.id.btnLogin);

        tvForgetPassword = findViewById(R.id.tvForgetPassword);
        etUserName = findViewById(R.id.userName);
        etPassword = findViewById(R.id.password);
        autoLogin = findViewById(R.id.autoLogin);

        //        this--context
        //给按钮添加点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("LoginActivity", "按钮被点击了，准备登录.......");
//                LoginActivity.this -- Context


                String username = etUserName.getText().toString();
                String password = etPassword.getText().toString();
                if (username == null || "".equals(username)) {
                    etUserName.setError("用户名不能为空");
                    return;
                }
                if (password == null || "".equals(password)) {
                    etPassword.setError("密码不能为空");
                    return;
                }


                login();
                //TODO 将用户名密码发送到 后端验证
                // admin   123456    etUserName.getText()--->Editable
//                if(!"admin".equals(username) || !"123456".equals(password) ){
//                    etUserName.setError("用户名或者密码不正确");
//                    return;
//                }
//
//                //保存自动登录信息
//                saveAutoLogin();
//
//
//                //构造跳转的意图
//                //从当前Activity,跳转到MainActivity
//                //Context packageContext, Class<?> cls
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
////
//                //关闭当前Activity
//                finish();
////                //使用意图启动Activity
//                startActivity(intent);
            }
        });

        tvForgetPassword.setText(Html.fromHtml("<a href=\"http://www.12306.cn\">忘记密码?</a>"));

        tvForgetPassword.setMovementMethod(LinkMovementMethod.getInstance());

    }


    //网络登录

    private void login() {

        String username = etUserName.getText().toString();
        String password = etPassword.getText().toString();

        //在开始网络请求之前 打开loading
        dialog = ProgressDialog.show(this, "", "登录中，请稍后",
                true,
                false);


        new Thread() {
            @Override
            public void run() {

                Message handlerMsg = handler.obtainMessage();
                try {
                    Log.d("LoginActivity", "username: " + username);
                    Log.d("LoginActivity", "password: " + password);
//                    String api = "http://www.fulfill.com.cn:3146/android-server/loginXml?username=" + username + "&password=" + password;
                    String api = "http://www.fulfill.com.cn:3146/android-server/loginJSON?username=" + username + "&password=" + password;
                    URL url = new URL(api);
                    URLConnection urlConnection = url.openConnection();
//                    urlConnection.connect();
                    InputStream is = urlConnection.getInputStream();

//                    Map result = parseXML(is);
                    Map result = parseJSON(is);
                    handlerMsg.what = 1;
                    handlerMsg.obj = result;
                    handler.sendMessage(handlerMsg);


                } catch (Exception e) {
                    //发起网络请求异常
                    //失败的情况
                    e.printStackTrace();
                    handlerMsg.what = 2;
                    Log.d("LoginActivity", "网络请求失败 ");
                }


            }
        }.start();
    }


    //从JSON String字符串  转换成Java 类型
    private Map parseJSON(InputStream is) {
        //json
        Gson gson = new GsonBuilder().create();

        //{"code":200,"message":"操作成功","obj":true}
        //{"code":500,"message":"用户名或密码不正确","obj":null}
        Map result = gson.fromJson(new InputStreamReader(is),Map.class);

        return result;
    }

    private Map parseXML(InputStream is) throws XmlPullParserException, IOException {
        //读取xml文件的内容
        double code = -1;
        String msg = "";
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "utf-8");
        while (parser.next() != XmlPullParser.END_DOCUMENT) {
            String tagName = parser.getName();
            if ("code".equals(tagName)) {
                code = Double.parseDouble(parser.nextText());
            }
            if ("msg".equals(tagName)) {
                msg = parser.nextText();
            }
        }

        Map result = new HashMap<>();
        result.put("code", code);
        result.put("message", msg);
        return result;
    }


    //自动登录的保存
    private void saveAutoLogin() {
        if (autoLogin.isChecked()) {

            Log.d("LoginActivity", "自动登录");
            String username = etUserName.getText().toString();
            String password = etPassword.getText().toString();


            SharedPreferences sp = getSharedPreferences("AUTO_LOGIN", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();

            edit.putString("username", username);
            edit.putString("password", password);

            edit.commit();//将数据写入到文件中

        } else {

            Log.d("LoginActivity", "非自动登录");
        }

    }


    @Override
    protected void onStart() {
        super.onStart();
        System.out.println("===onStart====");
    }

    @Override
    protected void onResume() {
        super.onResume();
        System.out.println("===onResume====");
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        System.out.println("===onRestart====");
    }

    @Override
    protected void onPause() {
        super.onPause();
        System.out.println("===onPause====");
    }

    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("===onStop====");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("===onDestroy====");

    }
}